{% extends "teacher/base.html" %}

{% block title %}班级对比分析 - 期末成绩登记统计分析系统{% endblock %}

{% block content %}
<div class="card mt-4">
  <div class="card-title">
    <i class="fas fa-chart-bar"></i>
    班级对比分析
    <div class="float-end">
      <select id="semesterSelect" class="form-select form-select-sm d-inline-block w-auto me-2">
        <option value="">全部学期</option>
      </select>
      <button class="btn btn-sm btn-outline-primary" onclick="toggleView()">
        <i class="fas fa-exchange-alt"></i> 切换视图
      </button>
    </div>
  </div>
  <div id="chartView" class="chart-container" style="position: relative; height:400px;">
    <canvas id="classComparisonChart"></canvas>
  </div>
  <div id="tableView" class="table-container" style="display: none;">
    <table class="table table-striped">
      <thead>
        <tr>
          <th class="text-center">班级</th>
          <th class="text-center">平均成绩</th>
        </tr>
      </thead>
      <tbody id="comparisonTableBody">
      </tbody>
    </table>
  </div>
  <div class="comparison-note mt-3">
    <p class="text-muted">
      <i class="fas fa-info-circle"></i>
      班级对比分析展示了不同班级的平均成绩情况，可以帮助教师了解各班级的学习水平和差异。
    </p>
  </div>
</div>
{% endblock %}

{% block styles %}
{{ super() }}
<link href="https://cdn.bootcdn.net/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css" rel="stylesheet">
<style>
  .chart-container {
    margin-top: 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .table-container {
    margin-top: 20px;
    background: white;
    border-radius: 10px;
    padding: 20px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  }

  .card {
    border: none;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    border-radius: 15px;
  }

  .card-title {
    padding: 20px;
    background: #e9eef4;
    color: #2c3e50;
    border-radius: 15px 15px 0 0;
    font-size: 1.2em;
  }

  .btn-outline-primary {
    border-color: #2c3e50;
    color: #2c3e50;
  }

  .btn-outline-primary:hover {
    background-color: white;
    color: #764ba2;
  }

  .main-content {
    margin-top: 70px !important;
  }

  .float-end {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-left: auto;
  }

  .comparison-note {
    padding: 15px;
    background: #f8f9fa;
    border-radius: 8px;
    font-size: 0.9em;
    margin: 20px;
  }

  .comparison-note i {
    color: #6c757d;
    margin-right: 5px;
  }

  .form-select {
    border-color: #2c3e50;
    color: #2c3e50;
    font-size: .875rem;
    padding: .45rem 2rem .45rem .75rem;
    border-radius: 0.25rem;
    transition: all 0.3s ease;
    background-color: white;
    cursor: pointer;
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 16 16'%3e%3cpath fill='none' stroke='%232c3e50' stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M2 5l6 6 6-6'/%3e%3c/svg%3e");
    background-repeat: no-repeat;
    background-position: right 0.75rem center;
    background-size: 16px 12px;
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
  }

  .form-select:focus {
    border-color: #764ba2;
    box-shadow: 0 0 0 0.2rem rgba(118, 75, 162, 0.25);
  }

  .form-select:hover {
    border-color: #764ba2;
  }

  .form-select option {
    padding: 8px;
  }

  .form-select option:hover {
    background-color: #f8f9fa;
  }
</style>
{% endblock %}

{% block scripts %}
{{ super() }}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.0/chart.min.js"></script>
<script>
  let chart = null;
  let comparisonData = null;
  let semesters = [];

  // 检查Chart.js是否加载成功
  function checkChartJsLoaded() {
    if (typeof Chart === 'undefined') {
      console.error('Chart.js 未加载成功');
      alert('图表库加载失败，请刷新页面重试');
      return false;
    }
    return true;
  }

  function toggleView(event) {
    if (event) {
      event.stopPropagation();
      event.preventDefault();
    }
    const chartView = document.getElementById('chartView');
    const tableView = document.getElementById('tableView');

    if (chartView.style.display !== 'none') {
      chartView.style.display = 'none';
      tableView.style.display = 'block';
      updateTable();
    } else {
      chartView.style.display = 'block';
      tableView.style.display = 'none';
    }
  }

  function updateTable() {
    if (!comparisonData) return;

    const tbody = document.getElementById('comparisonTableBody');
    tbody.innerHTML = '';

    comparisonData.labels.forEach((label, index) => {
      const row = document.createElement('tr');
      row.innerHTML = `
        <td class="text-center">${label}</td>
        <td class="text-center">${comparisonData.values[index]}</td>
      `;
      tbody.appendChild(row);
    });
  }

  function loadData(semester = '') {
    const url = semester ? `/teacher/analysis/data?semester=${semester}` : '/teacher/analysis/data';
    fetch(url)
      .then(response => {
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
      })
      .then(result => {
        if (result.success) {
          comparisonData = result.data.classComparison;
          semesters = result.data.semesters;

          // 更新学期选择器，倒序显示
          const semesterSelect = document.getElementById('semesterSelect');
          semesterSelect.innerHTML = '<option value="">全部学期</option>';
          semesters.slice().reverse().forEach(semester => {
            semesterSelect.innerHTML += `<option value="${semester}">${semester}</option>`;
          });
          if (semester) {
            semesterSelect.value = semester;
          }

          // 创建渐变色
          const ctx = document.getElementById('classComparisonChart').getContext('2d');
          const gradient = ctx.createLinearGradient(0, 0, 0, 400);
          gradient.addColorStop(0, 'rgba(54, 162, 235, 0.8)');
          gradient.addColorStop(1, 'rgba(54, 162, 235, 0.2)');

          if (chart) {
            chart.destroy();
          }

          chart = new Chart(ctx, {
            type: 'bar',
            data: {
              labels: comparisonData.labels,
              datasets: [{
                label: '班级平均分',
                data: comparisonData.values,
                backgroundColor: gradient,
                borderColor: 'rgba(54, 162, 235, 1)',
                borderWidth: 2,
                borderRadius: 5,
                hoverBackgroundColor: 'rgba(54, 162, 235, 0.9)'
              }]
            },
            options: {
              responsive: true,
              maintainAspectRatio: false,
              plugins: {
                legend: {
                  display: false
                },
                title: {
                  display: true,
                  text: '班级平均成绩对比',
                  font: {
                    size: 18,
                    family: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif"
                  },
                  padding: {
                    top: 10,
                    bottom: 30
                  }
                },
                tooltip: {
                  backgroundColor: 'rgba(0, 0, 0, 0.8)',
                  titleFont: {
                    size: 16
                  },
                  bodyFont: {
                    size: 14
                  },
                  padding: 12,
                  cornerRadius: 8,
                  displayColors: true
                }
              },
              animation: {
                duration: 2000,
                easing: 'easeOutQuart'
              },
              scales: {
                y: {
                  beginAtZero: true,
                  max: 100,
                  grid: {
                    color: 'rgba(0, 0, 0, 0.1)',
                    drawBorder: false
                  },
                  ticks: {
                    font: {
                      size: 12
                    }
                  }
                },
                x: {
                  grid: {
                    display: false
                  },
                  ticks: {
                    font: {
                      size: 12
                    }
                  }
                }
              }
            }
          });

          // 如果当前是表格视图，更新表格
          if (document.getElementById('tableView').style.display !== 'none') {
            updateTable();
          }
        } else {
          throw new Error(result.message || '获取数据失败');
        }
      })
      .catch(error => {
        console.error('Error:', error);
        const chartView = document.getElementById('chartView');
        chartView.innerHTML = `<div class="text-center p-5 text-danger"><i class="fas fa-exclamation-circle"></i> ${error.message || '获取数据失败，请稍后重试'}</div>`;
      });
  }

  document.addEventListener('DOMContentLoaded', function () {
    if (!checkChartJsLoaded()) return;

    loadData();

    // 监听学期选择变化
    document.getElementById('semesterSelect').addEventListener('change', function () {
      loadData(this.value);
    });
  });
</script>
{% endblock %}